 // 创建用户集合
// 引入mongoose第三方模块
const mongoose = require('mongoose');
// 导入bcrypt
const bcrypt = require('bcryptjs');
const uuid = require('uuid');
// 创建用户集合规则
const userSchema = new mongoose.Schema({
    user_id: {
        type: String,
        required: true,
        unique: true
    },
	nickname: {
		type: String,
		required: true,
        unique: true,
		minlength: 2,
		maxlength: 20
	},
    phoneNumber:{
        type: String,
        unique: true,
        minlength: 11,
        maxlength: 11
    },
	email: {
		type: String,
		// 保证邮箱地址在插入数据库时不重复
		unique: true,
		required: true
	},
	password: {
		type: String,
		required: true
	},
    avatar: {
        type: String,
    },
    sex: {
        type: String,
    },
    address: {
        type: String
    },
    signature: {
        type: String
    },   
    receivingAddress: {
        type: Array
    },
     //卖家简介
	summary:{
        type: String
    },
    follows:{
        type: Array
    },
    fans:{
        type: Array
    },
    //收藏的商品
    collections:{
        type: Array
    },                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
});

// 创建集合
const User = mongoose.model('User', userSchema);
const path = require('path')
async function createUser () {
	const salt = bcrypt.genSaltSync(10);
	const pass = bcrypt.hashSync('123456', salt);
    const avatarDir = "/uploads/images/avatar/portrait.jpg";
    const user_id = uuid.v1();
	const user = await User.create({
        user_id: user_id,
	    nickname: '醍醐向南山',
        phoneNumber: '13669320563',
		email: '1382916710@qq.com',
		password: pass,
        sex: "男",
        avatar: avatarDir,
        address: '广东广州',
        signature:'这个人什么都没留下...',
        receivingAddress: [],
        summary:"下单后24小时内发货，支持7天无理由退货",
        follows: [
        ],
        fans:[
        ],
        collections:[
        ]
	});
}

// createUser();
async function findUserByAccount(account){
  var user = await User.findOne({email:account})
  if(user == null){
    user = await User.findOne({phoneNumber:account})
  }
  if(user == null){
    user = await User.findOne({nickname:account})
  }
  return user;
}

// 将用户集合做为模块成员进行导出
module.exports = {
    User,
    findUserByAccount
};